package com.gcsoftware.authentications.shiro;

import com.gcsoftware.authentications.beans.RoleInfo;
import com.gcsoftware.authentications.beans.UserInfo;
import com.gcsoftware.authentications.helper.UserHelper;
import com.gcsoftware.utils.SpringContextUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * shiro realm验证
 * Created by qs on 2018/3/14.
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SpringContextUtils utils;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("doGetAuthorizationInfo:" + principalCollection.toString());

        UserInfo user = new UserHelper().getUserByName((String) principalCollection.getPrimaryPrincipal());

        //把principals放session中 key=userId value=principals
        SecurityUtils.getSubject().getSession().setAttribute(user.getUserId(),SecurityUtils.getSubject().getPrincipals());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (RoleInfo role : user.getUserRoles()) {
            info.addRole(role.getRoleName());
        }

        /*for (PermissionInfo permis : UserHelper.getPermissionsByUserId(user.getUserId())) {
            info.addStringPermission(permis.getPermisName());
        }*/


        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        logger.debug("The login userName is {} , and password is {}" , userName, token.getPassword());

        UserInfo user = new UserHelper().getUserByName(userName);
        if (null != user) {
            //设置用户session
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("user", user);
            return new SimpleAuthenticationInfo(userName,user.getUserPwd(), ByteSource.Util.bytes(user.getSalt()),getName());

        }
        return null;
    }
}
